﻿using System;
using System.Collections.Generic;
using Tareas.ServiceReference;
using Windows.Foundation;
using Windows.Graphics.Display;
using Windows.UI.StartScreen;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;

namespace Tareas
{
    public sealed partial class ProjectDetails
    {
        private TaskServiceClient client;

        public ProjectDetails()
        {
            InitializeComponent();
            client = new TaskServiceClient();
        }

        async void getTasks()
        {
            PageTitle.Text = project.Name + " (Cargando)";
            try
            {
                this.Items = await client.getTasksAsync(project.ProjectId);
                client.CloseAsync();
                PageTitle.Text = project.Name;
            }
            catch (Exception)
            {
                PageTitle.Text = "Se ha producido un error";
                //Show a Message dialog
            }

        }

        void ItemView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // TODO: Construct the appropriate destination page and set its context appropriately
        }

        private Project project;

        public Project Project
        {
            get { return project; }
            set
            {
                project = value;
                this.PageTitle.Text = project.Name;
                getTasks();
            }
        }

        private IEnumerable<Object> _items;
        public IEnumerable<Object> Items
        {
            get
            {
                return this._items;
            }

            set
            {
                this._items = value;
                CollectionViewSource.Source = value;
            }
        }

        // View state management for switching among Full, Fill, Snapped, and Portrait states

        private DisplayPropertiesEventHandler _displayHandler;
        private TypedEventHandler<ApplicationLayout, ApplicationLayoutChangedEventArgs> _layoutHandler;

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (_displayHandler == null)
            {
                _displayHandler = Page_OrientationChanged;
                _layoutHandler = Page_LayoutChanged;
            }
            DisplayProperties.OrientationChanged += _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged += _layoutHandler;
            SetCurrentViewState(this);
        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            DisplayProperties.OrientationChanged -= _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged -= _layoutHandler;
        }

        private void Page_LayoutChanged(object sender, ApplicationLayoutChangedEventArgs e)
        {
            SetCurrentViewState(this);
        }

        private void Page_OrientationChanged(object sender)
        {
            SetCurrentViewState(this);
        }

        private void SetCurrentViewState(Control viewStateAwareControl)
        {
            VisualStateManager.GoToState(viewStateAwareControl, this.GetViewState(), false);
        }

        private String GetViewState()
        {
            var orientation = DisplayProperties.CurrentOrientation;
            if (orientation == DisplayOrientations.Portrait ||
                orientation == DisplayOrientations.PortraitFlipped) return "Portrait";
            var layout = ApplicationLayout.Value;
            if (layout == ApplicationLayoutState.Filled) return "Fill";
            if (layout == ApplicationLayoutState.Snapped) return "Snapped";
            return "Full";
        }

        private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            App.ShowCollection();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            /*A new Task gets added*/
            client = new TaskServiceClient();
            await client.addTaskAsync(new Task() { RelatedProject = this.project, Title = tbNewTask.Text });

            /*The updated task list gets downloaded from the server*/
            this.Items = await client.getTasksAsync(project.ProjectId);
            client.CloseAsync();
        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Uri logo = new Uri("ms-resource:images/Logo.png");
            string tileActivationArguments = "ArgumentosDeActivacion";
            //Se genera el tile
            SecondaryTile secondaryTile = new SecondaryTile("Identificador",
                                                            "Acceso Secundario",
                                                            "Un ejemplo práctico",
                                                            tileActivationArguments,
                                                            TileDisplayAttributes.ShowName,
                                                            logo);
            //Se solicita al usuario que autorice la creación del tile.
            await secondaryTile.RequestCreateAsync();
        }
    }
}
